package com.galaxy.commom.base.handler;

import com.google.common.collect.Maps;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 统一全局的异常处理类 使用@ControllerAdvice控制器增强所有的@ExceptionHandler、@initBinder、@ModelAttribute的注解
 * 应用到所有的@RequestMapping注解的方法中
 *
 * @author caijinbang
 * @date 2018/9/17 12:56
 */
@ControllerAdvice
public class CommonExceptionHandler {

  public final static String DEFAULT_ERROR_VIEW="";

  /**
   * 拦截Exception类的异常,可以根据自己的业务需求定义不同的拦截方法，例如:权限异常、404异常、500异常等
   * @param e
   * @return
   */
  @ExceptionHandler(Exception.class)
  @ResponseBody
  public Map<String, Object> exceptionHandler(Exception e) {
    Map<String, Object> result = Maps.newHashMap();
    result.put("resCode", "9999");
    result.put("resMsg", e.getMessage());
    return result;
  }

  @ExceptionHandler(RuntimeException.class)
  public ModelAndView defaultErrorHandler(HttpServletRequest request,Exception e){
      ModelAndView modelAndView = new ModelAndView();
      modelAndView.addObject("exception",e);
      modelAndView.addObject("url",request.getRequestURL());
      modelAndView.setViewName(DEFAULT_ERROR_VIEW);
      return modelAndView;
  }
}
